<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title>缤格</title>
    <link rel="stylesheet" type="text/css" href="../../css/api.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/swiper.min.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/common.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/binge.css"/>
    <script type="text/javascript" src="../../script/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="../../script/swiper.min.js"></script>
    <script type="text/javascript" src="../../script/laydate/laydate.js"></script>
    <script type="text/javascript" src="../../script/mobile.js"></script>
    <script type="text/javascript">
        window['adaptive'].desinWidth = 750;
        window['adaptive'].baseFont = 28;
        window['adaptive'].maxWidth = 750;
        window['adaptive'].init();
    </script>
</head>

<body>
<!-- header -->
<div id="header" style="height: 0.9rem; background: #fff; position: fixed; top: 0;left: 0; width: 100%; z-index: 99; background: #fff;">
    <div class="header">
        <div class="head-back">
            <a href="javascript:void(0);" tapmode onclick="comeBack()">取消</a>
        </div>
        <div class="head-title">
            <h6>发布投票</h6>
        </div>
        <div class="head-action">
            <a href="javascript:void(0);" tapmode onclick="releaseVote()">发布</a>
        </div>
    </div>
</div>
<!-- header end -->
<div class="header-h" style="padding-top: 1.5rem;"></div>
<div class="activity-section">
    <div class="activity-detail" style="border-bottom: 0.15rem #f5f5f5 solid;">
        <textarea class="textarea" style="height: 1.5rem;" name="" id="content" cols="30" rows="10" placeholder="输入投票相关描述"></textarea>
    </div>
    <div class="vote-item">
        <ul>
            <li>
                <div class="upload-img bg-cover" tapmode onclick="upload(this)" style="">
                    <span tapmode onclick="removePic(this,event)" class="delete dn"></span>
                </div>
                <div class="item-text">
                    <textarea class='upload-txt' name="" id="" cols="30" rows="10" placeholder="选项1"></textarea>
                </div>
                <div class="delete-li"></div>
            </li>
            <li>
                <div class="upload-img bg-cover" tapmode onclick="upload(this)" style="">
                    <span tapmode onclick="removePic(this,event)" class="delete dn"></span>
                </div>
                <div class="item-text">
                    <textarea class='upload-txt' name="" id="" cols="30" rows="10" placeholder="选项2"></textarea>
                </div>
                <div class="delete-li"></div>
            </li>
        </ul>
        <div class="add-item">
            <div class="add" id="addItem">添加选项</div>
            <div class="note">最多支持12个选项，每个选项不超过40个字</div>
        </div>
    </div>

    <div class="fill-info" style="border-bottom: 0.15rem #f5f5f5 solid;">
        <ul>
            <li>
                <p class="label">投票类型</p>
                <div class="label-input">
                    <select class="selectInput" name="" id="kind">
                        <option value="1">单选</option>
                        <option value="2">多选</option>
                    </select>
                </div>
            </li>
            <li class="checkLi" style="display: none;">
                <p class="label">最多选择数量</p>
                <div class="label-input">
                    <select class="selectInput" name="" id="maxNum">
                    </select>
                </div>
            </li>
            <li class="checkLi" style="display: none;">
                <p class="label">最少选择数量</p>
                <div class="label-input">
                    <select class="selectInput" name="" id="minNum">
                    </select>
                </div>
            </li>
            <li>
                <p class="label">结束时间</p>
                <div class="label-input">
                    <input type="text" readonly class="chooseTime" id="endTime" value="">
                </div>
            </li>
        </ul>
    </div>

    <div class="vote-text-img">
        <div class="upload-img" tapmode onclick="upload(this,2)">
            <img src="" id='voteFm' alt="">
            <span tapmode onclick='removePic(this,event,2)' class="delete dn"></span>
        </div>
        <p>可上传一张和投票主题相关的图片</p>
    </div>

</div>


<!-- 时间选择器-->
<div class="model" style="display: none">
    <div class="model-time" id="modelTime"></div>
</div>
<!-- 时间选择器 end-->

</body>

</html>
<script type="text/javascript" src="../../script/api.js"></script>
<script type="text/javascript" src="../../script/common.js"></script>
<script type="text/javascript">
    var circle_id = '';//圈子id
    var voteKind = 1;//投票类型
    var voteKind_max = 1;//投票类型为多选时 最多选择
    var voteKind_min = 1;//投票类型为多选时 最少选择
    apiready = function () {

        setFixStatusBar(); //设置状态栏
        keybackListener()
        circle_id = api.pageParam.circle_id;
        // circle_id = 2;



    };

    $("#kind").change(function(){
        var _this = $(this);
        if(_this.val() == 2){
          voteKind = 2;//多选
          $("#maxNum").val(2)
        }else {
          voteKind = 1;//单选
          voteKind_max = 1;
          voteKind_min = 1;
        }
    })



    var num = 0;
    eachItemLi();//页面加载后排序
    //删除图片
    $(".vote-item").on("click",".delete",function () {
        var _this = $(this);
        _this.parents('.upload-img').attr("style",'');
        _this.hide();
    });

    //添加项
    $("#addItem").on("click",function () {
        if( num > 11 ){
            pop.notice('最多添加12个选项');
            return;
        }
        num++;
        var html = '<li>' +
            '                <div class="upload-img bg-cover" tapmode onclick="upload(this)" style="">' +
            '                    <span tapmode onclick="removePic(this,event)" class="delete dn"></span>' +
            '                </div>' +
            '                <div class="item-text">' +
            '                    <textarea class="upload-txt" name="" id="" cols="30" rows="10" placeholder="选项'+num+'"></textarea>' +
            '                </div>' +
            '                <div class="delete-li"></div>' +
            '            </li>'
        $(".vote-item ul").append(html);
        eachItemLi();
    });

    //删除项
    $(".vote-item").on("click",".delete-li",function () {
        var _this = $(this);
        _this.parents('li').remove();
        eachItemLi();
    });

    //循环命名
    function eachItemLi() {
        var eachNum = 0;
        var maxHtml = '',minHtml='';
        var len = $(".vote-item li").length;
        $(".vote-item li").each(function () {
            var _this = $(this);
            var _thisIndex = Number(_this.index()) + 1;
            // console.log(_thisIndex)
            _this.find('textarea').attr('placeholder','选项'+_thisIndex);
            eachNum++;

            if(_thisIndex != 1){
                //最多选择（非一项）
                maxHtml += '<option value="'+_thisIndex+'">'+_thisIndex+'</option>';
            }
            if(_thisIndex != len){
                //最少选择（非最多项）
                minHtml += '<option value="'+_thisIndex+'">'+_thisIndex+'</option>';
            }
        });
        num = eachNum;
        $("#maxNum").html(maxHtml);
        $("#minNum").html(minHtml);
    }
    //监听单选多选
    $("#kind").change(function () {
        var _this = $(this);
        if(_this.val() == 1){
            //单选
            $(".checkLi").hide();
        }else {
            $(".checkLi").show();
        }
    });

    var _timeModel = $(".model");
    var _chooseTime = '';
    $(".chooseTime").click(function () {
        _timeModel.fadeIn();
    });

    laydate.render({
        elem: '#modelTime', //指定元素
        position: 'static',
        type: 'datetime',
        trigger: 'click',
        format: 'yyyy-MM-dd HH:mm',
        btns: ['confirm'],
        done: function (value) {
             console.log(value);
            _chooseTime = value;
        }
    });
    //确定时间，关闭弹窗
    $(".laydate-btns-confirm").click(function () {
        $('#endTime').val(_chooseTime);
        console.log(_chooseTime);
        _timeModel.fadeOut();
    });

    _timeModel.on('click', function (e) {
        _timeModel.fadeOut();
    });



    //提交信息
    function releaseVote() {

        if(!isDefine($('#content').val())){
            pop.notice('请填写投票相关描述');
            return;
        }
        var item_icons = [];
        var item_contents = [];
        var len = $(".vote-item li").length;
        $(".vote-item li").each(function(index){
            var _this = $(this);
            var data_id = _this.find(".upload-img").attr('data-id')
            if(isDefine(data_id)){
              item_icons.push(data_id)
            }
            var _val = _this.find('.upload-txt').val();
            // console.log(getLength(_val))//判断字数
            if(getLength(_val) > 80 || getLength(_val) == 0){
              pop.notice('每个选项不得为空或者超过40个字');
              _this.find('.upload-txt').attr('style',"border: 1px #ff7777 solid;")
              return;
            } else {
              _this.find('.upload-txt').attr('style',"border: 1px transparent solid;")
              item_contents.push(_val)
            }
            len--;
            if(len == 0){

              if(!isDefine(item_icons.length)){
                  item_icons = 0
              }else {
                console.log(item_icons.length)
                if(item_icons.length > 0 && item_icons.length < $(".vote-item li").length){
                    pop.notice('请完善选项配图，或者取消所有配图')
                    return;
                }
              }

              if(!isDefine($('#endTime').val())){
                  pop.notice('请选择截止时间');
                  return;
              }

              var fmId = $('#voteFm').attr('data-id');
              if(!isDefine(fmId)){
                  fmId = 0
              }
              if(voteKind == 1){
                voteKind_max = 1;
                voteKind_min = 1;
              } else {
                voteKind_max = $("#maxNum").val();
                voteKind_min = $("#minNum").val();
              }

              var param = {
                  token: $api.getStorage('token'),
                  circle_id: circle_id,
                  title: $('#content').val(),
                  icon: fmId,//投票说明配图id
                  item_icons: item_icons,
                  item_contents: item_contents,
                  stype: voteKind,
                  many_number: voteKind_max,//最多选择条目数
                  less_number: voteKind_min,//最少选择条目数
                  over_time: $('#endTime').val(),//投票截止时间

              }

              console.log(jsonChange(param));
              // return;

              pop.loading();
              getAjax(Interface.release_vote, param, function (res) {

                  pop.notice(res.msg);
                  pop.close();
                  setTimeout(function () {
                      comeBack();
                      api.sendEvent({
                          name: 'activity',
                          extra: {}
                      });
                      api.sendEvent({
                          name: 'memberInfo',
                          extra: {}
                      });
                      api.sendEvent({
                          name: 'invitation',
                          extra: {}
                      });
                  },2000)
              }, function (error) {
                  pop.notice(error.msg);
                  pop.close();
              })

            }
        })



    }

    //上传图片
    function upload(that,m) {
        uploadHeadPic(function (res) {
          var _this = $(that);
          if(m != 2){
            _this.css({
              background:'url('+ajaxUrl + res.path+')'
            }).attr('data-id',res.icon);
          }else {
            _this.find('img').attr({
              'src': ajaxUrl + res.path,
              'data-id': res.icon
            });
          }
          _this.find('.delete').show();
            // icons.push(res.icon)
        })
    }

    //删除图片
    function removePic(that,event,m){
        event.stopPropagation();
        var _this = $(that);
        if(m != 2){
          _this.parents('.upload-img').css('background','').removeAttr('data-id');
        }else {
          _this.siblings('img').attr('src','').removeAttr('data-id');
        }
        _this.hide();
    }
    // $(".vote-item").on('click', '.delete', function (event) {
    //     event.stopPropagation();
    //     var _this = $(this);
    //     var re_id = _this.parents('.upload-img').css('background','').removeAttr('data-id');
    //     _this.hide();
    //     // icons.splice($.inArray(re_id, icons), 1);
    //     // console.log(jsonChange(icons))
    // });





</script>
